package com.daxt.common.util;

import net.sourceforge.tess4j.ITesseract;
import net.sourceforge.tess4j.Tesseract;
import net.sourceforge.tess4j.TesseractException;
import org.apache.commons.lang3.StringUtils;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class OcrUtil {

    /**
     * @param url 图片地址
     * @description: ocr获取内容   部署环境变量需要配置库“TESSDATA_PREFIX=D:\tessdata-main”
     * @author: lig
     * @date: 2022/2/15
     */
    public static String ocrImage(String url) {
        // 创建实例
        ITesseract instance = new Tesseract();

        // 设置识别语言
        instance.setLanguage("chi_sim");

//             加载语言，使用两种语言
//            instance.setLanguage("eng+chi_sim");

        // 设置识别引擎
        instance.setOcrEngineMode(0);

        // 读取文件

//            File src = new File("C:\\Users\\Administrator\\Desktop\\asd.jpg");
        String result = "";
        try {
            File src = new File(url);
            BufferedImage image = ImageIO.read(src);

            // 识别
            result = instance.doOCR(image);
//            System.out.println(result);
        } catch (TesseractException e) {
            System.err.println(e.getMessage());
        } catch (IOException e) {
            System.err.println(e.getMessage());
//            e.printStackTrace();
        }
        return result;
    }

    public static void main(String[] args){
        String str = ocrImage("D:\\home\\jar\\temp\\8657cfaf76eb97e2bd48b9837ddee726\\Image_0.png");
        System.err.println(str);


    }
}
